﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TimerTask.Common.Utils;
using TimerTask.Model.Entity;

namespace TimerTask.Service.NotifyTools
{

    public class SmsNotify : INotify
    {
        private SmsNotify() { }
        public void Notify(JobInfo job, bool isSuccessed, string res)
        {
            //助通科技
            string dtStr = DateTime.Now.ToString("yyyyMMddHHmmss");
            Dictionary<string, string> smsNotifyObj = new Dictionary<string, string>();
            smsNotifyObj.Add("username", UserName);
            smsNotifyObj.Add("tkey", dtStr);
            smsNotifyObj.Add("password", Md5Util.GetMd5(Md5Util.GetMd5(Pwd, string.Empty), dtStr));
            smsNotifyObj.Add("mobile", job.ContactTel);
            smsNotifyObj.Add("content", string.Format("[{0}]任务执行【{1}】DT:{2}", job.JobName, isSuccessed ? "恢复" : "失败", dtStr));
            try
            {
                string result = HttpUtil.DoGet(AppConfig.Instance.SmsNotify.ReqUrl, string.Empty, smsNotifyObj).GetAwaiter().GetResult();

                if (result.Split(',')[0] != "1")
                {
                    LogUtil.Error("发送短信失败Req：{0}；error：{1}", smsNotifyObj.ToJson(), result);
                }
            }
            catch (Exception exception)
            {
                LogUtil.Error(exception, "发送短信失败{0}", new { job, isSuccessed, res }.ToJson());
            }
        }

        public string UserName { get; set; }
        public string Pwd { get; set; }
        public string ReqUrl { get; set; }

        public const int NotifyCode = 2;

        private static SmsNotify _instance;
        public static SmsNotify Instance()
        {
            if (_instance == null)
            {
                _instance = new SmsNotify();
                _instance.Pwd = AppConfig.Instance.SmsNotify.Pwd;
                _instance.UserName = AppConfig.Instance.SmsNotify.UserName;
                _instance.ReqUrl = AppConfig.Instance.SmsNotify.ReqUrl;
            }
            return _instance;
        }
    }
}
